package com.tourism.core.mybatis.handler;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tourism.core.security.util.SecurityHolderUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自动设置创建人，创建时间，修改人，修改时间默认值
 *
 * @author wangbing
 */
@Component
public class DefaultDBFieldHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if(getFieldValByName("createTime", metaObject) == null){
            this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }

        if(getFieldValByName("updateTime", metaObject) == null){
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }

        Long userId = SecurityHolderUtils.getUserId();

        if(getFieldValByName("createBy", metaObject) == null && userId != null){
            this.setFieldValByName("createBy", userId, metaObject);
        }

        if(getFieldValByName("updateBy", metaObject) == null && userId != null){
            this.setFieldValByName("updateBy", userId, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if(getFieldValByName("updateTime", metaObject) == null){
            setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }

        Long userId = SecurityHolderUtils.getUserId();

        if(getFieldValByName("updateBy", metaObject) == null && userId != null){
            this.setFieldValByName("updateBy", userId, metaObject);
        }
    }
}
